from django.contrib.auth import login,logout,authenticate
from django.views.decorators.http import require_POST
from django.shortcuts import render,redirect,reverse
from .forms import SigninForm,SignupForm
from utils import restful
from utils.captcha.lincaptcha import Captcha
from io import BytesIO
from django.http import HttpResponse
from django.core.mail import send_mail
from django.conf import settings
from django.core.cache import cache
from django.contrib.auth import get_user_model
import re

User = get_user_model()

@require_POST
def login_view(request):
    form = SigninForm(request.POST)
    if form.is_valid():
        email = form.cleaned_data.get('email')
        password = form.cleaned_data.get('password')
        remember = form.cleaned_data.get('remember')
        user = authenticate(request,username=email,password=password)
        if user:
            if user.is_active:
                login(request,user)
                if remember:
                    request.session.set_expiry(None)
                else:
                    request.session.set_expiry(0)
                return restful.ok()
            else:
                return restful.unauth(message='您的账号已被冻结！')
        else:
            return restful.params_error(message='账号或密码输入错误！')
    else:
        print(form.get_error())
        return restful.params_error(message=form.get_error())

def logout_view(request):
    logout(request)
    return redirect(reverse('index'))

@require_POST
def register_view(request):
    form = SignupForm(request.POST)
    if form.is_valid():
        email = form.cleaned_data.get('email')
        username = form.cleaned_data.get('username')
        password = form.cleaned_data.get('password')
        user = User.objects.create_user(email=email,username=username,password=password)
        login(request,user)
        return restful.ok()
    else:
        return restful.params_error(message=form.get_error())

def img_captcha(request):
    text,img = Captcha.gene_code()
    out = BytesIO()
    img.save(out,'png')
    out.seek(0)
    response = HttpResponse(content_type='image/png')
    response.write(out.read())
    response['Content-length'] = out.tell()
    # 邮箱验证码过期时间是4分钟
    cache.set(text.lower(),text.lower(),4*60)
    return response

@require_POST
def email_captcha(request):
    email = request.POST.get('email','error')
    if re.match(r'[a-zA-Z0-9]+@[a-zA-Z0-9]+\.com',email):
        try:
            captcha = Captcha.gene_text()
            print('邮箱验证码是%s' % captcha)
            send_email(captcha,email)
            # 邮箱验证码过期时间是4分钟
            cache.set(email,captcha,4*60)
            return restful.ok()
        except:
            return restful.server_error(message='发送邮件失败！')
    else:
        return restful.params_error(message='请输入正确格式的邮箱！')


def send_email(captcha,recipient):
    message = '您正在进行注册操作，本次的验证码是 ' + str(captcha) + '，请注意查收!'
    send_mail(subject='linLinStyle',message=message,from_email=settings.EMAIL_HOST_USER,recipient_list=[recipient])